#include "epoll_loop.h"
#include "task.h"
#include "timer_loop.h"
#include "when_any.h"
#include <cerrno>
#include <coroutine>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <unistd.h>

using namespace std::chrono_literals;

co_async::TimerLoop timer_loop;
co_async::EpollLoop epoll_loop;

co_async::Task<> async_main() {

  int file = co_async::check_error(open("/dev/stdin", O_RDONLY | O_NONBLOCK));
  while (true) {
    auto s = co_await co_async::time_limit(
        timer_loop, co_async::read_string(&epoll_loop, file), 1s);
    if (s) {
      std::cout << "读到了" << *s << std::endl;
      if ((*s) == "quit\n") {
        break;
      }
    }
  }
}

int main() {

  ioctl(0, FIONBIO);

  auto t = async_main();

  t.get_handle().resume();
  while (!t.get_handle().done()) {
    auto delay = timer_loop.run();
    epoll_loop.run_once(delay);
  }
  return 0;
}